<template>
	<view>
		<view class="cart-container" v-if="cartList.length > 0">
			<!-- 地址 -->
			<myAddress></myAddress>
			<!-- 购物车商品列表的标题区域 -->
			<view class="">
				<view class="cart-title">
					<uni-icons type="shop" size="18"></uni-icons>
					<text class="cart-title-text">购物车</text>
				</view>
			</view>
			<!-- 购物车列表 -->
			<myCart :cartList='cartList' :number_box="true" :action="action" @deleted="deleted" @checkedBox="checkedBox"
				@gotoDetail="gotoDetail" @changenNum="changenNum"></myCart>
			<!-- 结算 -->
			<mySettle :total="total" @selectClick="selectAll" @settleAccounts="settleAccounts" ref="checkedActive"></mySettle>
		</view>
		<!-- 内容为空 -->
		<view class="" v-else>
			<myEmpty mode="car" @clickBnt="clickBnt" :IfShowBut='true'></myEmpty>
		</view>
		<!-- 提示框 -->
		<view class="" v-show="showModal">
			<myModal @cancel="cancel" @confirm="confirm" contents="确定要删除此商品吗?"></myModal>
		</view>
	</view>


</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import myMixins from "../../mixins/filterPrice.js"
	export default {
		data() {
			return {
				showModal: false, //提示框
				action: false, //是否可以平滑
				timer: '', //记录定时器状态
				deletedId: void 0, //删除商品id
				total: 0,
				cartList: [], //购物车列表
				activeDownRefresh: true //下拉执行闸
			};
		},
		mixins: [myMixins],
		computed: {
			...mapState("cart", ["cart"]),
			...mapState("login", ["token"]),
			...mapState("address", ["address"]),

		},
		watch: {
			cartList: {
				deep: true,
				handler() {
					this.getPrice() //价格0，则1500.00
					this.total = this.cartList.filter(item => item.goods_state).map(item => {
						return item.goods_count * item.goods_price
					}).reduce((pre, next) => {
						return pre + next
					}, 0)
				}
			}
		},
		onLoad() {
			this.init()
		},
		onShow() {
			uni.$setNavigationBarColor('tabBar')
		
			//tabBar数字图标显示
			this.init()
			uni.$logon()
		},
		//下拉刷新
		onPullDownRefresh() {
			if (this.activeDownRefresh) {
				this.init(() => uni.stopPullDownRefresh())
			}


		},
		//分享
		onShareAppMessage: function() {
			return {
				title: '“' + '”小程序,基于微慕WordPress版小程序构建',
				path: 'pages/index/index',
				appInfo: {
					'appId': config.appghId
				},
				success: function(res) {
					// 转发成功
				},
				fail: function(res) {
					// 转发失败
				}
			}
		},
		// 自定义分享朋友圈
		onShareTimeline: function() {
			return {
				title: '“' + '”小程序,基于微慕WordPress版小程序构建',
				path: 'pages/index/index',
			}
		},
		methods: {
			...mapMutations("cart", ["deleteCart"]),
			//购物列表
			init(Callback) {
				this.activeDownRefresh = false
				uni.$setTabBarBadge()
				this.cartList = this.cart
				this.action = false
				Callback && Callback()
				this.activeDownRefresh = true
			},
			//选择商品
			checkedBox(item) {
				item.goods_state = !item.goods_state
				//反向全选
				let stateAll = this.cartList.every(item => item.goods_state == true)
				if (stateAll) {
					return this.$refs.checkedActive.checked = true
				}
				this.$refs.checkedActive.checked = false
			},
			//商品数量加减
			changenNum(event) {
				this.cartList.filter(item => item.goods_id == event.name).forEach(item => item.goods_count = event.value)
			},
			//结算
			settleAccounts() {
				let emptyCart = this.cartList.some(item => item.goods_state == true)
				if (this.address.length == 0) {
					return uni.$showToast("请选择地址", "error")
				}
				if (!emptyCart) {
					return uni.$showToast("请选择商品", "error")
				}
				if (this.token == '') {
					return uni.$showToast("请登录", "error")
				}
				//  实现微信支付功能
				this.payOrder()
			},
			//实现微信支付功能
			async payOrder() {
				const orderInfo = {
					// 开发期间，注释掉真实的订单价格，
					// order_price: this.checkedGoodsAmount,
					// 写死订单总价为 1 分钱
					order_price: 0.01,
					// consignee_addr: this.addstr,
					consignee_addr: JSON.stringify(this.address[0]),
					goods: this.cart.filter(x => x.goods_state).map(x => ({
						goods_id: x.goods_id,
						goods_number: x.goods_count,
						goods_price: x.goods_price
					}))
				}
				console.log(orderInfo)
				// 1.2 发起请求创建订单
				const {
					data: res
				} = await uni.$http.post('/api/public/v1/my/orders/create', orderInfo)

				if (res.meta.status !== 200) return uni.$showToast('创建订单失败！', "error")
				uni.$showToast('创建订单成功')
				// 1.3 得到服务器响应的“订单编号”
				const orderNumber = res.message.order_number
				// 2. 获取订单预支付信息
				// 2.1 发起请求获取订单的支付信息
				const {
					data: res2
				} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
					order_number: orderNumber
				})

				// 2.2 预付订单生成失败
				if (res2.meta.status !== 200) return uni.$showToast('预付订单生成失败！', "error")
				// 2.3 得到订单支付相关的必要参数
				// const payInfo = res2.message.pay
				// 3.1 调用 uni.requestPayment() 发起微信支付
				// const [err, succ] = await uni.requestPayment(payInfo)
				// if (err) return uni.$showToast('订单未支付！',"error")
				// 3.3 完成了支付，进一步查询支付的结果
				// const { data: res3 } = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {order_number: orderNumber })
				const {
					data: res3
				} = await uni.$http.get('/api/public/v1/my/orders/all?number=2')
				// 3.4 检测到订单未支付
				if (res3.meta.status !== 200) return uni.$showToast('订单未支付！', "error")
				// 3.5 检测到订单支付完成
				uni.showToast({
					title: '预付订单生成！',
					icon: 'success',
					success() {
						uni.navigateTo({
							url: '/subUserInfo/order/order'
						})
					}
				})

			},
			//打开提示框
			deleted(e) {
				this.deletedId = e.name
				this.showModal = true
			},
			//关闭提示框
			cancel() {
				this.showModal = false
			},
			//删除商品
			confirm() {
				this.deleteCart(this.deletedId)
				this.init()
				this.cancel()
			},
			//全选，取消全选
			selectAll(checked) {
				this.cartList.forEach(item => {
					if (checked) {
						return item.goods_state = true
					}
					item.goods_state = false
				})
			},
			//跳转购物分类
			clickBnt() {
				uni.switchTab({
					url: "/pages/cate/cate"
				})
			},
			//跳转详情
			gotoDetail(item) {
				uni.navigateTo({
					url: '/subGoodsDetail/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},
		},
		onPageScroll(e) {
			// //解决平滑是滚动报错
			this.action = true //添加的class类名
			clearTimeout(this.timer) //这里必须要每次滚动前 清除一次
			// 如果停留则表示滚动结束  一旦空了1s就判定为滚动结束
			this.timer = setTimeout(() => {
				this.action = false //滚动结束清除class类名
			}, 500)
		}
	}
</script>

<style lang="scss">
	.cart-container {
		padding-bottom: 50px;
	}

	.cart-title {
		height: 80rpx !important;
		display: flex !important;
		align-items: center;
		font-size: 28rpx;
		padding-left: 10rpx;
		border-bottom: 2rpx solid #efefef;

		.cart-title-text {
			margin-left: 20rpx;
			font-weight: 600;
		}
	}



	//滑动单元格样式
	.u-page {
		padding: 0;
	}

	.u-demo-block__title {
		padding: 10px 0 2px 15px;
	}

	.swipe-action {
		&__content {
			padding: 25rpx 0;

			&__text {
				font-size: 15px;
				color: $u-main-color;
				padding-left: 30rpx;
			}
		}
	}
</style>